package com.songlin.houxin.admin.listeners;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.pig4cloud.plugin.excel.handler.ListAnalysisEventListener;
import com.pig4cloud.plugin.excel.kit.Validators;
import com.pig4cloud.plugin.excel.vo.ErrorMessage;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintViolation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author jinYuLinLang
 * @version 1.0.0
 * @ClassName ExcelListener.java
 * @Description <p></p>
 * @createTime 2022-06-02 17:43:00
 */
@Slf4j
public class ExcelListener extends ListAnalysisEventListener<Object> {

    private final List<Object> list = new ArrayList<>();

    private final List<ErrorMessage> errorMessageList = new ArrayList<>();

    private Long lineNum = 1L;

    @Override
    public void invoke(Object o, AnalysisContext analysisContext) {
        lineNum++;
        Object[] fieldsValue = ReflectUtil.getFieldsValue(o);
        boolean match = Arrays.stream(fieldsValue).allMatch(v -> ObjectUtil.isNull(v) || StrUtil.isBlank(v.toString()));
        if (!match) {
            Set<ConstraintViolation<Object>> violations = Validators.validate(o);
            if (!violations.isEmpty()) {
                Set<String> messageSet = violations.stream().map(ConstraintViolation::getMessage)
                        .collect(Collectors.toSet());
                errorMessageList.add(new ErrorMessage(lineNum, messageSet));
            } else {
                list.add(o);
            }
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.debug("Excel read analysed");
    }

    @Override
    public List<Object> getList() {
        return list;
    }

    @Override
    public List<ErrorMessage> getErrors() {
        return errorMessageList;
    }
}
